//////////////////////////////////////////////////////
// 程序名称：用Bresenham算法画线
// 功 能：能绘制任意斜率的直线，通过调用此函数绘制包含各种斜率的图案
// 编译环境：Visual Studio 2017，EasyX_20190219(beta)
// 作 者：xyqlx<mxxyqlx@qq.com>
// 最后修改：2019-3-7
#include <conio.h>
#include <graphics.h>
#include <cmath>

void Bresenham(int x1, int y1, int x2, int y2, COLORREF color);

int main()
{
	// 创建绘图窗口，大小为 640x480 像素
	initgraph(640, 480);
	//填充背景为白色
	setbkcolor(WHITE);
	cleardevice();
	//开始绘制
	setlinecolor(RED);

	//画从中心向四周辐射的多条线段
	const int n = 72;
	float PI = float(acos(0) * 2);
	for (int i = 0; i < n; i++) {
		int px = 320 + int(200 * cos(i * 2 * PI / n));
		int py = 240 + int(200 * sin(i * 2 * PI / n));
		Bresenham(320, 240, px, py, RED);
	}

	//结束绘制
	_getch();	 // 按任意键继续
	closegraph();	// 关闭绘图窗口
	return 0;
}

void Bresenham(int x1, int y1, int x2, int y2, COLORREF color)
{
	int x, y, dx, dy, i;
	int e;
	if(x1>x2){
		x1 ^= x2;
		x2 ^= x1;
		x1 ^= x2;
		y1 ^= y2;
		y2 ^= y1;
		y1 ^= y2;
	}
	x = x2 - x1;
	y = y2 - y1;
	if(y >= x){
		dx = x2 - x1;
		dy = y2 - y1;
		e = -dy;
		x = x1;
		y = y1;
		for (i = 0; i <= dy; i++)
		{
			putpixel(x, y, color);
			y++;
			e += 2 * dx;
			if (e >= 0)
			{
				x++;
				e -= 2 * dy;
			}
		}
	}
	else if(y <= x && y >= 0){
		dx = x2 - x1;
		dy = y2 - y1;
		e = -dx;
		x = x1;
		y = y1;
		for (i = 0; i <= dx; i++)
		{
			putpixel(x, y, color);
			x++;
			e += 2 * dy;
			if (e >= 0)
			{
				y++;
				e -= 2 * dx;
			}
		}
	}
	else if(y>=-x){
		dx = x2 - x1;
		dy = y1 - y2;
		e = -dx;
		x = x1;
		y = y1;
		for (i = 0; i <= dx; i++)
		{
			putpixel(x, y, color);
			x++;
			e += 2 * dy;
			if (e >= 0)
			{
				y--;
				e -= 2 * dx;
			}
		}
	}
	else{
		dx = x2 - x1;
		dy = y1 - y2;
		e = -dy;
		x = x1;
		y = y1;
		for (i = 0; i <= dy; i++)
		{
			putpixel(x, y, color);
			y--;
			e += 2 * dx;
			if (e >= 0)
			{
				x++;
				e -= 2 * dy;
			}
		}
	}
}
